package com.aeye.mbr.upms.rpc.service.impl;

import com.aeye.mbr.upms.dao.model.UpmsPermission;
import com.aeye.mbr.upms.dao.model.UpmsRolePermission;
import com.aeye.mbr.upms.dao.model.UpmsSystem;
import com.aeye.mbr.upms.dao.model.UpmsUserPermission;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.aeye.mbr.common.result.BootstrapTableParams;
import com.aeye.mbr.common.result.BootstrapTableResult;
import com.aeye.mbr.common.plugin.mapper.BaseServiceImpl;
import com.aeye.mbr.upms.rpc.mapper.UpmsPermissionMapper;
import com.aeye.mbr.upms.rpc.mapper.UpmsSystemMapper;
import com.aeye.mbr.upms.rpc.mapper.UpmsUserPermissionMapper;
import com.aeye.mbr.upms.rpc.api.UpmsApiService;
import com.aeye.mbr.upms.rpc.api.UpmsPermissionService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * UpmsPermissionService实现
 * Created by shuaeye.mbr on 2017/3/20.
 */
@Service
@Transactional
public class UpmsPermissionServiceImpl extends BaseServiceImpl<UpmsPermission> implements UpmsPermissionService {

    private static Logger _log = LoggerFactory.getLogger(UpmsPermissionServiceImpl.class);

    @Autowired
    UpmsSystemMapper upmsSystemMapper;

    @Autowired
    UpmsPermissionMapper upmsPermissionMapper;

    @Autowired
    UpmsApiService upmsApiService;

    @Autowired
    UpmsUserPermissionMapper upmsUserPermissionMapper;

    @Override
    public JSONArray getTreeByRoleId(Integer roleId) {
        // 角色已有权限
        List<UpmsRolePermission> rolePermissions = upmsApiService.selectUpmsRolePermisstionByUpmsRoleId(roleId);

        JSONArray systems = new JSONArray();

        Example example = new Example(UpmsSystem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", 1);
        example.setOrderByClause("AAA674 asc");
        // 系统
        List<UpmsSystem> upmsSystems = upmsSystemMapper.selectByExample(example);
        for (UpmsSystem upmsSystem : upmsSystems) {
            JSONObject node = new JSONObject();
            node.put("id", upmsSystem.getSystemId());
            node.put("name", upmsSystem.getTitle());
            node.put("nocheck", true);
            node.put("open", true);
            systems.add(node);
        }

        if (systems.size() > 0) {
            for (Object system : systems) {
                example = new Example(UpmsPermission.class);
                criteria = example.createCriteria();
                criteria.andEqualTo("status", 1);
                criteria.andEqualTo("systemId", ((JSONObject) system).getIntValue("id"));
                example.setOrderByClause("AAR010 asc");
                List<UpmsPermission> upmsPermissions = upmsPermissionMapper.selectByExample(example);
                if (upmsPermissions.size() == 0) continue;
                // 目录
                JSONArray folders = new JSONArray();
                for (UpmsPermission upmsPermission : upmsPermissions) {
                    if (upmsPermission.getPid().intValue() != 0 || upmsPermission.getType() != 1) continue;
                    JSONObject node = new JSONObject();
                    node.put("id", upmsPermission.getPermissionId());
                    node.put("name", upmsPermission.getName());
                    node.put("open", true);
                    for (UpmsRolePermission rolePermission : rolePermissions) {
                        if (rolePermission.getPermissionId().intValue() == upmsPermission.getPermissionId().intValue()) {
                            node.put("checked", true);
                        }
                    }
                    folders.add(node);
                    // 菜单
                    JSONArray menus = new JSONArray();
                    for (Object folder : folders) {
                        for (UpmsPermission upmsPermission2 : upmsPermissions) {
                            if (upmsPermission2.getPid().intValue() != ((JSONObject) folder).getIntValue("id") || upmsPermission2.getType() != 2)
                                continue;
                            JSONObject node2 = new JSONObject();
                            node2.put("id", upmsPermission2.getPermissionId());
                            node2.put("name", upmsPermission2.getName());
                            node2.put("open", true);
                            for (UpmsRolePermission rolePermission : rolePermissions) {
                                if (rolePermission.getPermissionId().intValue() == upmsPermission2.getPermissionId().intValue()) {
                                    node2.put("checked", true);
                                }
                            }
                            menus.add(node2);
                            // 按钮
                            JSONArray buttons = new JSONArray();
                            for (Object menu : menus) {
                                for (UpmsPermission upmsPermission3 : upmsPermissions) {
                                    if (upmsPermission3.getPid().intValue() != ((JSONObject) menu).getIntValue("id") || upmsPermission3.getType() != 3)
                                        continue;
                                    JSONObject node3 = new JSONObject();
                                    node3.put("id", upmsPermission3.getPermissionId());
                                    node3.put("name", upmsPermission3.getName());
                                    node3.put("open", true);
                                    for (UpmsRolePermission rolePermission : rolePermissions) {
                                        if (rolePermission.getPermissionId().intValue() == upmsPermission3.getPermissionId().intValue()) {
                                            node3.put("checked", true);
                                        }
                                    }
                                    buttons.add(node3);
                                }
                                if (buttons.size() > 0) {
                                    ((JSONObject) menu).put("children", buttons);
                                    buttons = new JSONArray();
                                }
                            }
                        }
                        if (menus.size() > 0) {
                            ((JSONObject) folder).put("children", menus);
                            menus = new JSONArray();
                        }
                    }
                }
                if (folders.size() > 0) {
                    ((JSONObject) system).put("children", folders);
                }
            }
        }
        return systems;
    }

    @Override
    public JSONArray getTreeByUserId(Integer userId, Byte type) {


        Example example = new Example(UpmsUserPermission.class);

        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("type", type);

        // 角色权限
        List<UpmsUserPermission> upmsUserPermissions = upmsUserPermissionMapper.selectByExample(example);

        JSONArray systems = new JSONArray();
        // 系统
        example = new Example(UpmsSystem.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("status", 1);
        example.setOrderByClause("AAA674 asc");
        List<UpmsSystem> upmsSystems = upmsSystemMapper.selectByExample(example);
        for (UpmsSystem upmsSystem : upmsSystems) {
            JSONObject node = new JSONObject();
            node.put("id", upmsSystem.getSystemId());
            node.put("name", upmsSystem.getTitle());
            node.put("nocheck", true);
            node.put("open", true);
            systems.add(node);
        }

        if (systems.size() > 0) {
            for (Object system : systems) {
                example = new Example(UpmsPermission.class);
                criteria = example.createCriteria();
                criteria.andEqualTo("status", 1);
                criteria.andEqualTo("systemId", ((JSONObject) system).getIntValue("id"));
                example.setOrderByClause("AAR010 asc");
                List<UpmsPermission> upmsPermissions = upmsPermissionMapper.selectByExample(example);
                if (upmsPermissions.size() == 0) continue;
                // 目录
                JSONArray folders = new JSONArray();
                for (UpmsPermission upmsPermission : upmsPermissions) {
                    if (upmsPermission.getPid().intValue() != 0 || upmsPermission.getType() != 1) continue;
                    JSONObject node = new JSONObject();
                    node.put("id", upmsPermission.getPermissionId());
                    node.put("name", upmsPermission.getName());
                    node.put("open", true);
                    for (UpmsUserPermission upmsUserPermission : upmsUserPermissions) {
                        if (upmsUserPermission.getPermissionId().intValue() == upmsPermission.getPermissionId().intValue()) {
                            node.put("checked", true);
                        }
                    }
                    folders.add(node);
                    // 菜单
                    JSONArray menus = new JSONArray();
                    for (Object folder : folders) {
                        for (UpmsPermission upmsPermission2 : upmsPermissions) {
                            if (upmsPermission2.getPid().intValue() != ((JSONObject) folder).getIntValue("id") || upmsPermission2.getType() != 2)
                                continue;
                            JSONObject node2 = new JSONObject();
                            node2.put("id", upmsPermission2.getPermissionId());
                            node2.put("name", upmsPermission2.getName());
                            node2.put("open", true);
                            for (UpmsUserPermission upmsUserPermission : upmsUserPermissions) {
                                if (upmsUserPermission.getPermissionId().intValue() == upmsPermission2.getPermissionId().intValue()) {
                                    node2.put("checked", true);
                                }
                            }
                            menus.add(node2);
                            // 按钮
                            JSONArray buttons = new JSONArray();
                            for (Object menu : menus) {
                                for (UpmsPermission upmsPermission3 : upmsPermissions) {
                                    if (upmsPermission3.getPid().intValue() != ((JSONObject) menu).getIntValue("id") || upmsPermission3.getType() != 3)
                                        continue;
                                    JSONObject node3 = new JSONObject();
                                    node3.put("id", upmsPermission3.getPermissionId());
                                    node3.put("name", upmsPermission3.getName());
                                    node3.put("open", true);
                                    for (UpmsUserPermission upmsUserPermission : upmsUserPermissions) {
                                        if (upmsUserPermission.getPermissionId().intValue() == upmsPermission3.getPermissionId().intValue()) {
                                            node3.put("checked", true);
                                        }
                                    }
                                    buttons.add(node3);
                                }
                                if (buttons.size() > 0) {
                                    ((JSONObject) menu).put("children", buttons);
                                    buttons = new JSONArray();
                                }
                            }
                        }
                        if (menus.size() > 0) {
                            ((JSONObject) folder).put("children", menus);
                            menus = new JSONArray();
                        }
                    }
                }
                if (folders.size() > 0) {
                    ((JSONObject) system).put("children", folders);
                }
            }
        }
        return systems;
    }


    @Override
    public BootstrapTableResult<UpmsPermission> selectUpmsPermissionByParams(BootstrapTableParams params,int type,int systemId) {
        BootstrapTableResult result = new BootstrapTableResult();
        if(params!=null){
            PageHelper.startPage(params.getPage(),params.getLimit());
            Example upmsPermissionExample = new Example(UpmsPermission.class);
            Example.Criteria criteria = upmsPermissionExample.createCriteria();
            if (0 != type) {
                criteria.andEqualTo("type",(byte) type);
            }
            if (0 != systemId) {
                criteria.andEqualTo("systemId",systemId);
            }
            String sort = params.getSort();
            String order = params.getOrder();
            if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
                upmsPermissionExample.setOrderByClause(sort + " " + order);
            }
            String search = params.getSearch();
            if (StringUtils.isNotBlank(search)) {
                upmsPermissionExample.or()
                        .andLike("name","%" + search + "%");
            }

            List<UpmsPermission> permissions = upmsPermissionMapper.selectByExample(upmsPermissionExample);
            if (!CollectionUtils.isEmpty(permissions)) {
                if (permissions instanceof Page) {
                    Page<UpmsPermission> pls = (Page) permissions;
                    result.setTotal((int) pls.getTotal());
                    result.setRows(pls.getResult());
                } else {
                    result.setTotal(permissions.size());
                    result.setRows(permissions);
                }
            }


        }

        return result;
    }
}